package main

import (
	"db-sharding/config"
	"db-sharding/proxy"
	"db-sharding/system/redis"
	"flag"
	"os"
	"os/signal"
	"runtime"
	"syscall"

	"db-sharding/system/log4go"
)

var configPath *string = flag.String("config", "etc", "config file path")

func main() {
	runtime.GOMAXPROCS(runtime.NumCPU())

	//解析配置文件路径
	flag.Parse()
	if len(*configPath) == 0 {
		log4go.Error("must use a config file")
		return
	}

	//初始化日志配置
	log4go.LoadConfiguration(*configPath + "/log4go.xml")
	defer log4go.Close()

	//初始化数据库配置
	err := config.ParseConfigFile(*configPath + "/db-sharding.yaml")
	if err != nil {
		log4go.Error(err.Error())
		return
	}

	redis.CreatePool(config.GlobalCfg.Redis)
	redis.LoadAll()

	var svr *proxy.Server
	svr, err = proxy.NewServer(config.GlobalCfg)
	if err != nil {
		log4go.Error(err.Error())
		return
	}

	sc := make(chan os.Signal, 1)
	signal.Notify(sc,
		syscall.SIGHUP,
		syscall.SIGINT,
		syscall.SIGTERM,
		syscall.SIGQUIT)

	go func() {
		sig := <-sc
		log4go.Info("Got signal [%d] to exit.", sig)
		svr.Close()
	}()

	svr.Run()
}
